package com.p2p.Androidp2p;

import java.io.File;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.os.Environment;
import android.util.Log;

public class Peer {
	//variables for the file you are about to download
	private static String delims = "[<>]+";
	
	/**
	 * searches the FileList for the file name passed in
	 * @param filename - filename the client is searching for
	 * @return - 0 if it was able to parse the message, -1 otherwise
	 */
	public static ArrayList<HashMap<String, String>> searchFileList(String filename)
	{
		String actionType = "getFileList";
		String actionParams = "<getFileList>";
		actionParams = actionParams.concat(filename);
		actionParams = actionParams.concat("</getFileList>");
		byte[] ret = Database.queryServer(actionType, actionParams);

		if(ret == null)
		{
		    return parse("<FileList></FileList>");
		}
		//parse through the file list returned, this will change due to several hits
		String xml = new String(ret);
		return parse(xml);
	}
	
	 /**
	 * searches HolderList on DB user's ip address and port number 
	 * @param id - file id of the file searched
	 * @return - 0 if it was able to parse the message, -1 otherwise
	 */
	public static String[] searchHolderList(String id)
	{
		//gets the holder list of the file that you choose
    	String actionType = "getHolderList";
    	String actionParams = "<getHolderList>";
    	actionParams = actionParams.concat(id);
    	actionParams = actionParams.concat("</getHolderList>");
    	byte[] ret = Database.queryServer(actionType, actionParams);
 		
    	//parses through the holder list, not sure if this will change
    	String parse = new String(ret);
    	String[]info = parse.split(delims);
    	
    	if(info.length < 6)
    	{
    		return null;
    	}
    	
    	String[] rets = new String[3];
    	//username
    	rets[0] = info[4];
    	//ip address
    	rets[1] = info[7];
    	//port number
    	rets[2] = info[10];
 
    	return rets;
	}
	
	/**
	 * starts the client class and begins transfer of files between client and server
	 * @param ip - the hosts ip address
	 * @param size - size of the file
	 * @param port - port that is open on host side
	 * @param filename - name of file that client is acquiring
	 */
	public static void startClient(String ip, int size, int port, String filename, String checksum)
	{
		Clientp2p client = new Clientp2p(ip,size,port,filename, checksum);
		Thread clientThread = new Thread(client);
		clientThread.start();
	}
	
	/**
	 * updates the database
	 * @return - 0 if the update succeeded and -1 otherwise
	 */
	public static int update()
	{
		String actionType = "register";
		File sdCard = Environment.getExternalStorageDirectory();
		File Shared = new File(sdCard,"Shared");
		
		//getting user name and port number
		String [] children = Shared.list();
		
		//make this a file to check instead
		String temp = "<Register><Username>"+AndroidP2P.getUsername()+"</Username><Port>3400</Port>";
		String actionParams = null;
		
		//loops through all files inside the shared folder
		if(children != null)
		{
			for(int index = 0; index < children.length; index++)
			{
				
				File file = new File(Shared, children[index]);

				temp = temp.concat("<File><Name>"+children[index] +"</Name>" +
						"<Size>"+ file.length() +"</Size>" +"</File>");
			}
		}
			
		//registers those files
		actionParams = temp.concat("</Register>");
		byte[] ret = Database.queryServer(actionType, actionParams);
		if(ret  == null)
		{
			return -1;
		}
		return 0;
	}

	/**
	 * parses through the string dat which is an xml string.
	 * will return a hashmap of the contents of the string that will be displayed
	 * 
	 */
	private static ArrayList<HashMap<String, String>> parse(String dat)
	{
	    try{
		/* Get a SAXParser from the SAXPArserFactory. */ 
		SAXParserFactory factory = SAXParserFactory.newInstance(); 
		SAXParser parser = factory.newSAXParser(); 
		
		/* Get the XMLReader of the SAXParser we created. */ 
		XMLReader xmlReader = parser.getXMLReader();
		ParseHandler handler = new ParseHandler();
		xmlReader.setContentHandler(handler);
		
		StringReader t2 = new StringReader(dat);
		InputSource xml = new InputSource(t2);
		xmlReader.parse(xml);
		return handler.getData();
	    }catch(Exception e)
	    {
		Log.d("AndroidP2P", e.getMessage());
		return null;
	    }
	}


}
